package com.vegetable.modules.controller.baseData;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.style.StyleUtil;
import com.alibaba.fastjson.JSON;
import com.vegetable.common.annotation.SysLog;
import com.vegetable.common.utils.ExcelUtils;
import com.vegetable.common.utils.PageUtils;
import com.vegetable.common.utils.R;
import com.vegetable.modules.controller.AbstractController;
import com.vegetable.modules.entity.baseData.ProductSpec;
import com.vegetable.modules.entity.baseData.Products;
import com.vegetable.modules.entity.baseData.po.ProductsAddPO;
import com.vegetable.modules.entity.inbound.excel.ProductsImport;
import com.vegetable.modules.entity.quotation.Quotation;
import com.vegetable.modules.entity.quotation.QuotationArea;
import com.vegetable.modules.service.baseData.IProductSpecService;
import com.vegetable.modules.service.baseData.IProductsService;
import com.vegetable.modules.service.quotation.IQuotationAreaService;
import com.vegetable.modules.service.quotation.IQuotationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 产地商品 前端控制器
 * </p>
 *
 * @author wangruijie
 * @since 2024-03-04
 */
@Slf4j
@RestController
@RequestMapping("/products")
@AllArgsConstructor
@Api(value = "产地商品", tags = "产地商品")
public class ProductsController extends AbstractController {

    private IProductsService productsService;
    private IQuotationService iQuotationService;

    private IProductSpecService iProductSpecService;
    private IQuotationAreaService quotationAreaService;


    /**
     * 所有产地商品列表
     */
    @GetMapping("/list")
    @ApiOperation(value = "条件查询产地商品列表", notes = "条件查询产地商品列表")
    public R list(@RequestParam Map<String, Object> params){
        log.info("条件查询产地商品列表{}", JSON.toJSONString(params));
        PageUtils page = productsService.queryPage(params);

        return R.data( page);
    }


    /**
     * 所有产地商品列表
     */
    @GetMapping("/listProducts")
    @ApiOperation(value = "条件查询产地商品列表", notes = "条件查询产地商品列表")
    public R listProducts(@RequestParam Map<String, Object> params){
        log.info("条件查询产地商品列表{}", JSON.toJSONString(params));
        PageUtils page = productsService.listProducts(params);

        return R.data( page);
    }

    /**
     * 产地商品信息
     */
    @GetMapping("/info/{id}")
    @ApiOperation(value = "产地商品信息", notes = "产地商品信息")
    public R info(@PathVariable("id") Long id){
        Products products = productsService.getById(id);
        return R.data(products);
    }

    /**
     * 保存产地商品
     */
    @SysLog(value = "保存产地商品", recordEntityChange = true, entityClass = Products.class)
    @PostMapping("/save")
    @ApiOperation(value = "保存产地商品", notes = "保存产地商品")
    public R save(@Validated @RequestBody ProductsAddPO po){
        QuotationArea area = quotationAreaService.quotationArea(po.getPlaceOrigin());
        if(Objects.isNull(area)){
            return R.fail("产地" + po.getPlaceOrigin() + "不存在");
        }
        Products products = new Products();
        BeanUtils.copyProperties(po, products);
        products.setAreaId(area.getId());
        // 商品编码组成：产地标识 + 商品分类 + 顺序数字
        String commonCode = area.getAreaSign() + productsService.getNextCode();
        products.setCommonCode(commonCode);
        // todo 设置
        products.setCreateUserId(getUserId());
        products.setStandardName(products.getCommonName() + products.getStandardWeight() + products.getCommonCode());
        // 根据地区查询
        if(StrUtil.isNotBlank(po.getQuotationName())){
//            Quotation quotation = iQuotationService.queryByCommodityNameAndArea(po.getQuotationName(), area.getId());
//            if(Objects.isNull(quotation)){
//                throw new RuntimeException("报价商品不存在，请确认商品名称/产地是否一致");
//            }
            Quotation quotation = checkQuotation(po.getQuotationName(), area.getId(), po.getCategory());
            products.setQuotationId(quotation.getId());
            products.setQuotationName(quotation.getProductName());
        }
        productsService.save(products);
        return R.status(true);
    }

    /**
     * 修改产地商品
     */
    @SysLog(value = "修改产地商品", recordEntityChange = true, entityClass = Products.class)
    @PostMapping("/update")
    @ApiOperation(value = "修改产地商品", notes = "修改产地商品")
    public R update(@RequestBody Products products){
        Products exist = productsService.getById(products.getId());
        if(Objects.isNull(exist)){
            return R.fail("修改的商品不存在.");
        }
        products.setCreateUserId(getUserId());
        products.setStandardName(products.getCommonName() + products.getStandardWeight() + products.getCommonCode());
        if(StrUtil.isNotBlank(products.getQuotationName())){
            Quotation quotation = checkQuotation(products.getQuotationName(), exist.getAreaId(), products.getCategory());
            products.setQuotationId(quotation.getId());
            products.setQuotationName(quotation.getProductName());
        }
        productsService.updateById(products);
        return R.status(true);
    }

    private Quotation checkQuotation(String quotationName, Long areaId, String productCategory) {
        if("小包装".equals(productCategory)){
            areaId = 12L;
        }else if("".equals(productCategory)){

        }
        Quotation quotation = iQuotationService.queryByCommodityNameAndArea(quotationName, areaId);
        if(Objects.isNull(quotation)){
            throw new RuntimeException("报价商品不存在，请确认商品名称/产地是否一致");
        }
        return quotation;
    }

    /**
     * 删除产地商品
     */
    @SysLog(value = "删除产地商品", recordEntityChange = true, entityClass = Products.class)
    @GetMapping("/delete")
    @ApiOperation(value = "删除产地商品", notes = "删除产地商品")
    public R delete(Long id){
        productsService.removeById(id);
        return R.status(true);
    }

    @GetMapping("/enabled")
    @ApiOperation(value = "启用/禁用产地商品", notes = "启用/禁用产地商品")
    public R enabled(Long id, Integer isEnabled){
        Products products = new Products();
        products.setId(id);
        products.setIsEnabled(isEnabled);
        productsService.updateById(products);
        return R.status(true);
    }

    @PostMapping("/exportTemplate")
    @ApiOperation(value = "导出商品列表", notes = "导出商品列表")
    public R exportTemplate() throws IOException {
        List<ProductsImport> orderList = new ArrayList<>();
        Map<String, Object> params = new HashMap<>();
        params.put("isEnabled", "0");
        params.put("tags", "2");
        params.put("limit", Long.MAX_VALUE+"");
        PageUtils page = productsService.queryPage(params);
        if(CollectionUtil.isNotEmpty(page.getList())){
            for(Object p : page.getList()){
                ProductsImport im = new ProductsImport();
                BeanUtils.copyProperties(p, im);
                orderList.add(im);
            }
        }
        if(CollectionUtil.isNotEmpty(orderList)){
            List<Long> productIds = orderList.stream().map(el -> el.getId()).collect(Collectors.toList());
            List<ProductSpec> specList = iProductSpecService.queryByProductIds(productIds);
            for(ProductsImport im : orderList){
                List<ProductSpec> specs = specList.stream().filter(el -> el.getProducerId().equals(im.getId())).collect(Collectors.toList());
                if(CollectionUtil.isNotEmpty(specs)){
                    Set<String> nameSet = specs.stream().map(el -> el.getName()).collect(Collectors.toSet());
                    im.setSpecsName(String.join("|", nameSet));
                }
            }
        }
        // 生成导出excel对象
        ExportParams exportParams = new ExportParams();
        exportParams.setSheetName("商品列表");
        //开始导出
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, ProductsImport.class, orderList);
        workbook.createCellStyle();
        StyleUtil.createHeadCellStyle(workbook);

        String fileName = "商品列表" + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        ExcelUtils.downLoadExcel(fileName,workbook);
        return R.success("");
    }
    
    /**
     * 单独修改商品图片
     */
    @SysLog(value = "修改商品图片", recordEntityChange = true, entityClass = Products.class)
    @PostMapping("/updateImage")
    @ApiOperation(value = "修改商品图片", notes = "单独修改商品图片链接")
    public R updateImage(@RequestBody Products product) {
        // 检查商品是否存在
        Products exist = productsService.getById(product.getId());
        if(Objects.isNull(exist)){
            return R.fail("商品不存在");
        }
        
        // 只更新图片链接字段
        Products updateProduct = new Products();
        updateProduct.setId(product.getId());
        updateProduct.setImageUrl(product.getImageUrl());
        
        productsService.updateById(updateProduct);
        return R.status(true);
    }
}